package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import luanvan.app.foodnote.library.Food;
import luanvan.app.foodnote.library.FoodAdapter;
import luanvan.app.foodnote.library.ParcelableFood;
import luanvan.app.foodnote.library.Sectionizer;
import luanvan.app.foodnote.library.SimpleSectionAdapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

public class FoodInCityActivity extends SherlockActivity implements LocationListener {

	private static final String TAG_CITY = "THANH_PHO";
	
	private FoodAdapter foodAdapter;
	
	private LocationManager locationManager;
	private String provider;
	private double getLat, getLng;
	private String fid, lat, lng;
	
	private static final int TEN_METERS = 10; // 10 meters
    private static final int TWO_MINUTES = 1000 * 60 * 2; // 2 minutes
	
	// Progress Dialog
	private ProgressDialog pDialog;
	
	private ListView listFood;
	// ArrayList thats going to hold the search results
	private List<Food> searchResults;
	// ArrayList that will hold the original Data
	private ArrayList<Food> originalValues;
	
	private static final String TAG_ID = "id";
	private static final String TAG_LAT = "LATITUDE";
	private static final String TAG_LNG = "LONGITUDE";
	
	// Edit search
	private EditText inputSearch;
		
	// Search options
    int searchOptions = 1;
	
	private TextWatcher textWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence cs, int start, int before,
				int count) {
			String searchString = inputSearch.getText().toString();
			int textLength = searchString.length();
			searchResults.clear();
			for(int i = 0; i < originalValues.size(); i++){
				
				if(searchOptions ==  1){
					String foodName = originalValues.get(i).getFood_name().toString();
					if(textLength <= foodName.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodName.substring(0, textLength))){
							searchResults.add(originalValues.get(i));
							Collections.sort(searchResults);
						}
					}
				} else if(searchOptions == 2){
					String foodDist = originalValues.get(i).getDistrict().toString();
					if(textLength <= foodDist.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodDist.substring(0, textLength))){
							searchResults.add(originalValues.get(i));
							Collections.sort(searchResults);
						}
					}
				} 
			}
			//adapter.getFilter().filter(cs.toString());
			foodAdapter.notifyDataSetChanged();
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_places);
		
		listFood = (ListView) findViewById(R.id.listFood);
		
		inputSearch = (EditText) findViewById(R.id.inputSearch);
		
		Intent i = getIntent();
		String nameCity = i.getStringExtra("nameCity");
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.city));
		getSupportActionBar().setTitle(nameCity);
		getSupportActionBar().show();
		
		originalValues = new ArrayList<Food>();
		
		
		new LoadFoodByCity().execute();
		
		// register Context Menu
		this.regisContextMenu();
				
		// Search food
		inputSearch.addTextChangedListener(this.textWatcher);
		
		// Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			System.out.println("Best Available provider " + provider + " has been selected.");
			this.onLocationChanged(location);
			//locationManager.requestLocationUpdates(provider, TEN_METERS, TWO_MINUTES, this);
			
			//Log.d("Location", String.valueOf(getLat) + ", " + String.valueOf(getLng));
		}
		else {
			Log.d("Location", "No location");
		}
	}
	
	// Load Food
	private class LoadFoodByCity extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(FoodInCityActivity.this);
			// pDialog.setIcon(R.drawable.help);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang tải danh sách ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected String doInBackground(String... agrs) {
			// TODO Auto-generated method stub
			Food.action = 2;
			ArrayList<ParcelableFood> foodsExtra = getIntent().getParcelableArrayListExtra(TAG_CITY);
			originalValues = new ArrayList<Food>();
			for (ParcelableFood food : foodsExtra) {
				originalValues.add(food.getFood());
			}
			searchResults = new ArrayList<Food>(originalValues);
				
			return null;
		}
		
		protected void onPostExecute(String file_url) {
			
			pDialog.dismiss();
			
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					foodAdapter = new FoodAdapter(FoodInCityActivity.this, R.layout.row, searchResults);
					// Wrap your existing adapter with the SimpleSectionAdapter
					Collections.sort(searchResults);
					SimpleSectionAdapter<Food> sectionAdapter = new SimpleSectionAdapter<Food>(getApplicationContext(), foodAdapter,
							R.layout.section_header, R.id.title, new FoodSectionizer());
					listFood.setAdapter(sectionAdapter);
					listFood.setFastScrollEnabled(true);
				}
			});
		}
		
	}
	
    
    class FoodSectionizer implements Sectionizer<Food>{

		@Override
		public String getSectionTitleForItem(Food instance) {
			// TODO Auto-generated method stub
			return instance.getDistrict();
		}
    	
    }
    
    @Override
    public void onBackPressed() {
		 super.onBackPressed();
    	 Food.action = 1;
		 return;
	 }
    
    /** Callback function */
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_foods_in_city, menu);
		
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
	    switch(item.getItemId()){
	    
	    case R.id.searchName:
	    	searchOptions = 1;
	    	return true;
	    	
	    case R.id.search_quan_huyen:
	    	searchOptions = 2;
	    	return true;
	    }	
	    return false; 
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Tùy chọn");
		menu.setHeaderIcon(R.drawable.submenu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.foods_in_city_ctx, menu);
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Long id = listFood.getItemIdAtPosition(info.position);
		//Long id = getListAdpter.getItemId(info.position);
		Log.d("id = ", String.valueOf(id));
		switch (item.getItemId()) {
		case R.id.update:
			Intent intentFoodPlace = new Intent(FoodInCityActivity.this,
					EditFoodActivity.class);
			intentFoodPlace.putExtra(TAG_ID, fid);
			Log.d("FOOD_ID", fid);
			startActivityForResult(intentFoodPlace, 100);
			return true;

		case R.id.food_places:
			Intent googlePlaces = new Intent(FoodInCityActivity.this,
					GooglePlacesActivity.class);
			googlePlaces.putExtra(TAG_LAT, Double.valueOf(lat));
			googlePlaces.putExtra(TAG_LNG, Double.valueOf(lng));
			startActivity(googlePlaces);
			return true;

		case R.id.direction:
			String dirMap = "http://maps.google.com/maps?";
			StringBuffer sBuf = new StringBuffer(dirMap);
			sBuf.append("saddr=");
			sBuf.append(getLat);
			sBuf.append(',');
			sBuf.append(getLng);
			sBuf.append("&daddr=");
			sBuf.append(Double.valueOf(lat));
			sBuf.append(',');
			sBuf.append(Double.valueOf(lng));
			Intent direction = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(sBuf.toString()));
			startActivity(direction);
			return true;
		
		}
		return (super.onOptionsItemSelected(item));
	}
	
	private void regisContextMenu(){
		
		registerForContextMenu(listFood);
		
		listFood.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				fid = ((TextView) view.findViewById(R.id.fid)).getText()
						.toString();
				lat = ((TextView) view.findViewById(R.id.lat)).getText()
						.toString();
				lng = ((TextView) view.findViewById(R.id.lng)).getText()
						.toString();
				// showDialog(CONTEXT_MENU_ID);
				openContextMenu(view);
			}
		});
	}

	 @Override
	 protected void onResume() {
		 super.onResume();
		 locationManager.requestLocationUpdates(provider, TEN_METERS, TWO_MINUTES, this);
	 }

	 @Override
	 protected void onPause() {
		 super.onPause();
	    locationManager.removeUpdates(this);
	 }
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		getLat = location.getLatitude();
		getLng = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
